import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import '../models/mood_record.dart';
import '../models/mood_type.dart';
import '../constants/app_theme.dart';

/// 自定义日历组件
/// 用于显示情绪记录的日历视图，支持事件标记和日期选择
class CalendarWidget extends StatefulWidget {
  /// 记录列表
  final List<MoodRecord> records;
  
  /// 选中日期回调
  final Function(DateTime selectedDay, DateTime focusedDay)? onDaySelected;
  
  /// 初始选中日期
  final DateTime? initialSelectedDay;
  
  /// 初始焦点日期
  final DateTime? initialFocusedDay;
  
  /// 日历格式
  final CalendarFormat initialFormat;
  
  /// 是否显示格式切换按钮
  final bool showFormatButton;
  
  /// 是否显示外部日期
  final bool showOutsideDays;
  
  /// 自定义样式
  final CalendarStyle? customStyle;
  
  /// 自定义头部样式
  final HeaderStyle? customHeaderStyle;

  const CalendarWidget({
    super.key,
    required this.records,
    this.onDaySelected,
    this.initialSelectedDay,
    this.initialFocusedDay,
    this.initialFormat = CalendarFormat.month,
    this.showFormatButton = true,
    this.showOutsideDays = false,
    this.customStyle,
    this.customHeaderStyle,
  });

  @override
  State<CalendarWidget> createState() => _CalendarWidgetState();
}

class _CalendarWidgetState extends State<CalendarWidget> {
  late DateTime _focusedDay;
  DateTime? _selectedDay;
  late CalendarFormat _calendarFormat;
  
  @override
  void initState() {
    super.initState();
    _focusedDay = widget.initialFocusedDay ?? DateTime.now();
    _selectedDay = widget.initialSelectedDay;
    _calendarFormat = widget.initialFormat;
  }

  /// 判断两个日期是否为同一天
  bool _isSameDay(DateTime? a, DateTime? b) {
    if (a == null || b == null) return false;
    return a.year == b.year && a.month == b.month && a.day == b.day;
  }

  /// 获取指定日期的记录
  List<MoodRecord> _getRecordsForDay(DateTime day) {
    return widget.records.where((record) {
      return _isSameDay(record.createdAt, day);
    }).toList();
  }

  /// 获取日期的情绪颜色（基于当天最强烈的情绪）
  Color? _getMoodColorForDay(DateTime day) {
    final dayRecords = _getRecordsForDay(day);
    if (dayRecords.isEmpty) return null;
    
    // 找到强度最高的记录
    final strongestRecord = dayRecords.reduce((a, b) {
      return a.intensity > b.intensity ? a : b;
    });
    
    return strongestRecord.moodType.color;
  }

  /// 构建日期标记
  Widget _buildEventMarker(DateTime day, List<MoodRecord> events) {
    if (events.isEmpty) return const SizedBox.shrink();
    
    final moodColor = _getMoodColorForDay(day);
    
    return Container(
      margin: const EdgeInsets.only(top: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 6,
            height: 6,
            decoration: BoxDecoration(
              color: moodColor ?? AppTheme.primaryColor,
              shape: BoxShape.circle,
            ),
          ),
          if (events.length > 1) ...[
            const SizedBox(width: 2),
            Text(
              '${events.length}',
              style: TextStyle(
                fontSize: 10,
                color: moodColor ?? AppTheme.primaryColor,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: TableCalendar<MoodRecord>(
        firstDay: DateTime.utc(2020, 1, 1),
        lastDay: DateTime.utc(2030, 12, 31),
        focusedDay: _focusedDay,
        selectedDayPredicate: (day) => _isSameDay(_selectedDay, day),
        calendarFormat: _calendarFormat,
        eventLoader: _getRecordsForDay,
        startingDayOfWeek: StartingDayOfWeek.monday,
        
        // 日历样式
        calendarStyle: widget.customStyle ?? CalendarStyle(
          outsideDaysVisible: widget.showOutsideDays,
          weekendTextStyle: TextStyle(
            color: AppTheme.textSecondaryColor,
          ),
          holidayTextStyle: TextStyle(
            color: AppTheme.primaryColor,
          ),
          selectedDecoration: BoxDecoration(
            color: AppTheme.primaryColor,
            shape: BoxShape.circle,
          ),
          selectedTextStyle: const TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
          todayDecoration: BoxDecoration(
            color: AppTheme.primaryColor.withOpacity(0.5),
            shape: BoxShape.circle,
          ),
          todayTextStyle: const TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
          defaultDecoration: const BoxDecoration(
            shape: BoxShape.circle,
          ),
          weekendDecoration: const BoxDecoration(
            shape: BoxShape.circle,
          ),
          outsideDecoration: const BoxDecoration(
            shape: BoxShape.circle,
          ),
          markerDecoration: BoxDecoration(
            color: AppTheme.accentColor,
            shape: BoxShape.circle,
          ),
          markersMaxCount: 1,
          canMarkersOverflow: false,
        ),
        
        // 头部样式
        headerStyle: widget.customHeaderStyle ?? HeaderStyle(
          formatButtonVisible: widget.showFormatButton,
          titleCentered: true,
          formatButtonShowsNext: false,
          formatButtonDecoration: BoxDecoration(
            color: AppTheme.primaryColor,
            borderRadius: BorderRadius.circular(12),
          ),
          formatButtonTextStyle: const TextStyle(
            color: Colors.white,
            fontSize: 12,
          ),
          leftChevronIcon: Icon(
            Icons.chevron_left,
            color: AppTheme.textPrimaryColor,
          ),
          rightChevronIcon: Icon(
            Icons.chevron_right,
            color: AppTheme.textPrimaryColor,
          ),
          titleTextStyle: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        
        // 自定义事件标记构建器
        calendarBuilders: CalendarBuilders(
          markerBuilder: (context, day, events) {
            return _buildEventMarker(day, events);
          },
          // 自定义选中日期样式
          selectedBuilder: (context, day, focusedDay) {
            final moodColor = _getMoodColorForDay(day);
            return Container(
              margin: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: moodColor ?? AppTheme.primaryColor,
                shape: BoxShape.circle,
                border: Border.all(
                  color: Colors.white,
                  width: 2,
                ),
              ),
              child: Center(
                child: Text(
                  '${day.day}',
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            );
          },
          // 自定义今天日期样式
          todayBuilder: (context, day, focusedDay) {
            final moodColor = _getMoodColorForDay(day);
            return Container(
              margin: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: (moodColor ?? AppTheme.primaryColor).withOpacity(0.7),
                shape: BoxShape.circle,
              ),
              child: Center(
                child: Text(
                  '${day.day}',
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            );
          },
          // 自定义有事件的日期样式
          defaultBuilder: (context, day, focusedDay) {
            final moodColor = _getMoodColorForDay(day);
            if (moodColor == null) return null;
            
            return Container(
              margin: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: moodColor.withOpacity(0.2),
                shape: BoxShape.circle,
                border: Border.all(
                  color: moodColor,
                  width: 1,
                ),
              ),
              child: Center(
                child: Text(
                  '${day.day}',
                  style: TextStyle(
                    color: moodColor,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            );
          },
        ),
        
        // 事件回调
        onDaySelected: (selectedDay, focusedDay) {
          setState(() {
            _selectedDay = selectedDay;
            _focusedDay = focusedDay;
          });
          widget.onDaySelected?.call(selectedDay, focusedDay);
        },
        onFormatChanged: (format) {
          setState(() {
            _calendarFormat = format;
          });
        },
        onPageChanged: (focusedDay) {
          setState(() {
            _focusedDay = focusedDay;
          });
        },
      ),
    );
  }
}

/// 紧凑型日历组件
/// 用于在较小空间内显示日历
class CompactCalendarWidget extends StatelessWidget {
  /// 记录列表
  final List<MoodRecord> records;
  
  /// 选中日期回调
  final Function(DateTime selectedDay)? onDaySelected;
  
  /// 初始选中日期
  final DateTime? initialSelectedDay;
  
  /// 显示的月份
  final DateTime displayMonth;

  CompactCalendarWidget({
    super.key,
    required this.records,
    this.onDaySelected,
    this.initialSelectedDay,
    DateTime? displayMonth,
  }) : displayMonth = displayMonth ?? DateTime.now();

  /// 判断两个日期是否为同一天
  bool _isSameDay(DateTime? a, DateTime? b) {
    if (a == null || b == null) return false;
    return a.year == b.year && a.month == b.month && a.day == b.day;
  }

  /// 获取指定日期的记录数量
  int _getRecordCountForDay(DateTime day) {
    return records.where((record) {
      return _isSameDay(record.createdAt, day);
    }).length;
  }

  /// 获取日期的情绪颜色
  Color? _getMoodColorForDay(DateTime day) {
    final dayRecords = records.where((record) {
      return _isSameDay(record.createdAt, day);
    }).toList();
    
    if (dayRecords.isEmpty) return null;
    
    final strongestRecord = dayRecords.reduce((a, b) {
      return a.intensity > b.intensity ? a : b;
    });
    
    return strongestRecord.moodType.color;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: AppTheme.dividerColor,
        ),
      ),
      child: TableCalendar(
        firstDay: DateTime.utc(2020, 1, 1),
        lastDay: DateTime.utc(2030, 12, 31),
        focusedDay: displayMonth,
        selectedDayPredicate: (day) => _isSameDay(initialSelectedDay, day),
        calendarFormat: CalendarFormat.month,
        headerVisible: false,
        daysOfWeekVisible: false,
        
        calendarStyle: CalendarStyle(
          outsideDaysVisible: false,
          cellMargin: const EdgeInsets.all(2),
          defaultDecoration: const BoxDecoration(),
          selectedDecoration: BoxDecoration(
            color: AppTheme.primaryColor,
            shape: BoxShape.circle,
          ),
          todayDecoration: BoxDecoration(
            color: AppTheme.primaryColor.withOpacity(0.5),
            shape: BoxShape.circle,
          ),
        ),
        
        calendarBuilders: CalendarBuilders(
          defaultBuilder: (context, day, focusedDay) {
            final recordCount = _getRecordCountForDay(day);
            final moodColor = _getMoodColorForDay(day);
            
            return GestureDetector(
              onTap: () => onDaySelected?.call(day),
              child: Container(
                margin: const EdgeInsets.all(1),
                decoration: BoxDecoration(
                  color: moodColor?.withOpacity(0.2),
                  shape: BoxShape.circle,
                  border: moodColor != null
                      ? Border.all(color: moodColor, width: 1)
                      : null,
                ),
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        '${day.day}',
                        style: TextStyle(
                          fontSize: 10,
                          color: moodColor ?? AppTheme.textPrimaryColor,
                          fontWeight: recordCount > 0
                              ? FontWeight.bold
                              : FontWeight.normal,
                        ),
                      ),
                      if (recordCount > 0)
                        Container(
                          width: 4,
                          height: 4,
                          decoration: BoxDecoration(
                            color: moodColor ?? AppTheme.primaryColor,
                            shape: BoxShape.circle,
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

/// 月份选择器
/// 用于快速切换月份
class MonthSelector extends StatelessWidget {
  /// 当前月份
  final DateTime currentMonth;
  
  /// 月份变化回调
  final Function(DateTime month) onMonthChanged;
  
  /// 可选择的最早月份
  final DateTime? earliestMonth;
  
  /// 可选择的最晚月份
  final DateTime? latestMonth;

  const MonthSelector({
    super.key,
    required this.currentMonth,
    required this.onMonthChanged,
    this.earliestMonth,
    this.latestMonth,
  });

  /// 获取月份名称
  String _getMonthName(int month) {
    const monthNames = [
      '一月', '二月', '三月', '四月', '五月', '六月',
      '七月', '八月', '九月', '十月', '十一月', '十二月'
    ];
    return monthNames[month - 1];
  }

  /// 检查是否可以导航到上个月
  bool _canNavigateToPrevious() {
    if (earliestMonth == null) return true;
    final previousMonth = DateTime(currentMonth.year, currentMonth.month - 1);
    return previousMonth.isAfter(earliestMonth!) ||
           previousMonth.isAtSameMomentAs(earliestMonth!);
  }

  /// 检查是否可以导航到下个月
  bool _canNavigateToNext() {
    if (latestMonth == null) return true;
    final nextMonth = DateTime(currentMonth.year, currentMonth.month + 1);
    return nextMonth.isBefore(latestMonth!) ||
           nextMonth.isAtSameMomentAs(latestMonth!);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: AppTheme.dividerColor,
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
            onPressed: _canNavigateToPrevious()
                ? () {
                    final previousMonth = DateTime(
                      currentMonth.year,
                      currentMonth.month - 1,
                    );
                    onMonthChanged(previousMonth);
                  }
                : null,
            icon: const Icon(Icons.chevron_left),
            iconSize: 20,
          ),
          GestureDetector(
            onTap: () {
              // 显示月份选择对话框
              _showMonthPicker(context);
            },
            child: Text(
              '${currentMonth.year}年 ${_getMonthName(currentMonth.month)}',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: AppTheme.textPrimaryColor,
              ),
            ),
          ),
          IconButton(
            onPressed: _canNavigateToNext()
                ? () {
                    final nextMonth = DateTime(
                      currentMonth.year,
                      currentMonth.month + 1,
                    );
                    onMonthChanged(nextMonth);
                  }
                : null,
            icon: const Icon(Icons.chevron_right),
            iconSize: 20,
          ),
        ],
      ),
    );
  }

  /// 显示月份选择对话框
  void _showMonthPicker(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择月份'),
        content: SizedBox(
          width: 300,
          height: 300,
          child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              childAspectRatio: 2,
            ),
            itemCount: 12,
            itemBuilder: (context, index) {
              final month = index + 1;
              final monthDate = DateTime(currentMonth.year, month);
              final isSelected = month == currentMonth.month;
              
              return GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                  onMonthChanged(monthDate);
                },
                child: Container(
                  margin: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: isSelected
                        ? AppTheme.primaryColor
                        : AppTheme.surfaceColor,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(
                      color: isSelected
                          ? AppTheme.primaryColor
                          : AppTheme.dividerColor,
                    ),
                  ),
                  child: Center(
                    child: Text(
                      _getMonthName(month),
                      style: TextStyle(
                        color: isSelected
                            ? Colors.white
                            : AppTheme.textPrimaryColor,
                        fontWeight: isSelected
                            ? FontWeight.bold
                            : FontWeight.normal,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}